package src.main.java.fr.oasisteam;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

public abstract class HibernateDaoSupport<T extends Serializable> implements
		DaoItf<T>
{
	private Class<T> clazz;

	@Autowired
	SessionFactory sessionFactory;

	public void setClazz(final Class<T> clazzToSet)
	{
		clazz = clazzToSet;
	}

	@Override
	@Transactional
	public void save(T entity)
	{
		Transaction transaction = this.getCurrentSession().beginTransaction();
		this.getCurrentSession().saveOrUpdate(entity);
		transaction.commit();
	}

	@Override
	@Transactional
	public void update(T entity)
	{
		this.getCurrentSession().merge(entity);
	}

	@Override
	@Transactional
	public void delete(T entity)
	{
		this.getCurrentSession().delete(entity);
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public T get(long id)
	{
		Transaction transaction = this.getCurrentSession().beginTransaction();

		try
		{
			T myEntity = (T) this.getCurrentSession().get(this.clazz, id);
			transaction.commit();
			return myEntity;
		} catch (Exception e)
		{
			transaction.rollback();
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional
	public List<T> get()
	{
		Transaction transaction = this.getCurrentSession().beginTransaction();
		List<T> list = this.getCurrentSession()
				.createQuery("from " + this.clazz.getName()).list();

		transaction.commit();

		return list;
	}

	@Override
	@Transactional
	public void delete(long id)
	{
		this.getCurrentSession().delete(this.get(id));
	}

	public final Session getCurrentSession()
	{
		return sessionFactory.getCurrentSession();
	}
}
